import { createEditor } from './create';

export interface Options {
    el: string;
    width?: number;
    height?: number;
  }

export class Editor {
    private options: Options;
    private dom: HTMLElement | null;
    private selection: Selection | null | undefined;
    private range: Range | undefined;
  
    constructor(options: Options) {
      this.options = options;
      this.selection = window.getSelection();
      this.dom = document.querySelector(this.options.el) as HTMLElement;
      if (this.dom) {
        createEditor(this.dom, this);
      } else {
        throw new Error(`${this.options.el} target element not found!`);
      }
    }

    exec(cmd: string, showUI: boolean = false, value: string = '') {
      document.execCommand(cmd, showUI, value);
    }
  
    setRange() {
      const { selection } = this;
      if (selection && !selection?.isCollapsed) {
        const range = selection?.getRangeAt(0);
        this.range = range;
      }
    }
  
    recoverRange() {
      const { selection, range } = this;
      if (selection && range) {
        if (selection.rangeCount > 0) selection.removeAllRanges();
        selection?.addRange(range.cloneRange());
      }
    }
  }